<script lang="ts" setup>
import type { Recordable } from '@vben/types';
import { ref } from 'vue';
import dayjs, { Dayjs } from 'dayjs';
import { message } from 'ant-design-vue';
import { useVbenModal } from '@vben/common-ui';
import { handleOrderdataApi } from '#/api';
import { Description, useDescription } from '#/components';

import { descriptionSchema, testItemsOptions, samplePropOptions } from './schemas';

const record = ref(); // 记录调用modal时传递过来的数据

/* 通过弹窗方式加载当前内容 */
const [VbenModal, modalApi] = useVbenModal({
  // fullscreen: true,  // 默认全屏
  confirmText: '关闭',
  draggable: true,
  closeOnPressEscape: false,
  closeOnClickModal: false,
  showCancelButton: false,

  onOpenChange(isOpen) {
    // 判断是打开还是关闭
    if (!isOpen) {
      return;
    }
    record.value = modalApi.getData()?.record || {};

    // 处理数据
    processData(record.value?.orderNo)
      .then((res) => {
        descMethods.setDescProps({ data: res });
      })
      .catch((err: any) => {
        message.error(err.message);
      });
  },
  onConfirm() {
    modalApi.close();
  },
  onCancel() {
    modalApi.close();
  },
});

const [register, descMethods] = useDescription({
  title: '委托单详情',
  showTitle: false,
  colon: true,
  size: 'default',
  bordered: true,
  column: { md: 3, sm: 1, xs: 1 },
  schema: descriptionSchema,
  labelStyle: { width: '150px', textAlign: 'right' },
});

/*==============================函数过程===============================*/
async function processData(orderNo: any) {
  try {
    let results = <Recordable>{};
    // 处理表单数据
    results = await handleOrderdataApi('getInfo', orderNo);
    if (results.length > 1) {
      return new Error('获取数据失败，数据长度大于1！');
    } else if (results.length === 0) {
      return new Error('未获取到数据！');
    }

    /*========== 数据清洗 =========*/
    results = results[0];
    // 处理数组字段
    const fields = ['sampleProp', 'testItems'];
    fields.forEach((item) => {
      if (results[item] && typeof results[item] === 'string') {
        try {
          results[item] = JSON.parse(results[item]);
        } catch (error) {
          return new Error(`处理字段 ${item}时出错:`, error);
        }
      }
    });

    results.testItems = translateField(results.testItems, testItemsOptions);
    results.sampleProp = translateField(results.sampleProp, samplePropOptions);
    // 如果results.invoiceTitle为null或空字符串，则将其设置为'无'；为undefined则设置为'未填写',否则保持原样
    if (results.invoiceTitle === null || results.invoiceTitle === '') {
      results.invoiceTitle = 2;
    } else if (results.invoiceTitle === undefined) {
      results.invoiceTitle = 3;
    }
    if (results.invoiceMailing === null || results.invoiceMailing === '') {
      results.invoiceMailing = 2;
    } else if (results.invoiceMailing === undefined) {
      results.invoiceMailing = 3;
    }

    // 处理日期字段
    const dateFields = ['orderDate'];
    dateFields.forEach((item) => {
      if (results[item]) {
        results[item] = <Dayjs>dayjs(results[item]).format('YYYY年MM月DD日');
      }
    });

    return results;
  } catch (error) {
    throw new Error(error.message);
  }
}

/**
 * 根据options数组中的value值，将field数组中的值转换为对应的label值
 * @field 需转换的数组
 * @options 转换的对照数组
 * @return 转换后的字符串，以“、”分隔
 */
function translateField(field: any, options: any) {
  // 将数组中的每个元素转换为对应的label
  const optionsMap = options.reduce((acc: any, cur: any) => {
    acc[cur.value] = cur.label;
    return acc;
  }, {});
  if (Array.isArray(field)) {
    return field.map((item: any) => optionsMap[item]).join('、'); // 使用join将数组转换为字符串，以“、”分隔
  } else if (field.startsWith('[') && field.endsWith(']')) {
    return JSON.parse(field)
      .map((item: any) => optionsMap[item])
      .join('、');
  } else {
    return optionsMap[field];
  }
}

/*==============================其他事件===============================*/

defineExpose(modalApi);
</script>

<template>
  <VbenModal title="委托单" class="w-[90%] h-auto">
    <!-- <Description title="基础示例" :column="3" :data="descData" :schema="descriptionSchema" /> -->

    <Description @register="register" class="mt-4" />
  </VbenModal>
</template>
